package it.sd.wdc.spider.repository.template;

import java.util.Iterator;
import java.util.LinkedList;

public class AbstractNode  {
	
	protected LinkedList<AbstractNode> figli = new LinkedList<AbstractNode>();
	private AbstractNode parent = null;
	private int position = 0;
	
	public void addFiglio(AbstractNode node) {
		figli.add(node);
		node.setPosition(figli.size());
		node.setParent(this);
	}
	
	public void delete() {
		parent.delete(this);
	}
	
	public void delete(AbstractNode node) {
		
		for (Iterator<? extends AbstractNode> it=iterateFigli(); it.hasNext(); ) {
			AbstractNode figlio = it.next();
			if (node.equals(figlio)) {
				it.remove();
				break;
			}
			
		}
		
		getRoot().recompute();
		
	}

	public void recompute() {
		
		int p = 0;
		
		for (Iterator<? extends AbstractNode> it=iterateFigli(); it.hasNext(); ) {
			AbstractNode figlio = it.next();
			p++;
			figlio.setPosition(p);
			figlio.recompute();
		}
	}
	
	public void setParent(AbstractNode node) {
		this.parent = node;
	}
	
	public Iterator<? extends AbstractNode> iterateFigli() {
		return figli.iterator();
	}

	public boolean isRoot() {
		return (parent==null);
	}
	
	public AbstractNode getRoot() {
		if (parent==null) {
			return this;
		} else {
			return parent.getRoot();
		}
	}
	
	private void setPosition(int numero) {
		this.position = numero;
	}
	private int getPosition() {
		return this.position;
	}

	protected String getUniquePath() {
		StringBuffer b = new StringBuffer();
		
		if (parent!=null) {
			b.append(parent.getUniquePath() + ".");
		}
		
		b.append(this.getPosition());
		
		return b.toString();
	}
	
	public boolean isEqual(AbstractNode node) {
		return node.getUniquePath().equals(getUniquePath());
	}
	

	
}
